package session;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

import javax.servlet.http.Cookie;

import appserver.Constants;

public class SSMCookie extends Cookie {
	private static final boolean DEBUG = true;
	private String sessionId;
	private int sessionVersion;
	private String IPPrimary;
	private String IPBackup;
	
	public SSMCookie(String name, String cookieValue) {
		super(name,cookieValue);
		String value = null;
		try {
			value = URLDecoder.decode(cookieValue, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			System.out.println("Malformed cookie received: bad encoding");
			return;
		}
		if (value == null) {
			return; 
		}
		if (DEBUG) System.out.println("Cookie value found:" + value);
		String[] values = value.split(Constants.COOKIE_SEPARATOR);
		if (values.length != 4) {
			return;
		}
		this.sessionId = values[0];
		this.sessionVersion = Integer.parseInt(values[1]);
		this.IPPrimary = values[2];
		this.IPBackup = values[3];
	}
	
	public SSMCookie(Cookie cookie) {
		this(cookie.getName(),cookie.getValue());
	}
	
	/**
	 * returns a String with the correct cookie value format, used to build cookie to return
	 * to client
	 * @param sessionId
	 * @param sessionVersion
	 * @param IPPrimary
	 * @param IPBackup
	 * @return
	 */
	public static String buildStandardValue(String sessionId, int sessionVersion, String IPPrimary, String IPBackup) {
		String sep = Constants.COOKIE_SEPARATOR;
		String value = sessionId + sep + sessionVersion + sep + IPPrimary + sep + IPBackup;
		try {
			return URLEncoder.encode(value, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * @return the sessionId
	 */
	public String getSessionId() {
		return sessionId;
	}

	/**
	 * @param sessionId the sessionId to set
	 */
	public void setSessionId(String sessionId) {
		this.sessionId = sessionId;
	}

	/**
	 * @return the sessionVersion
	 */
	public int getSessionVersion() {
		return sessionVersion;
	}

	/**
	 * @param sessionVersion the sessionVersion to set
	 */
	public void setSessionVersion(int sessionVersion) {
		this.sessionVersion = sessionVersion;
	}

	/**
	 * @return the iPPrimary
	 */
	public String getIPPrimary() {
		return IPPrimary;
	}

	/**
	 * @param iPPrimary the iPPrimary to set
	 */
	public void setIPPrimary(String iPPrimary) {
		IPPrimary = iPPrimary;
	}

	/**
	 * @return the iPBackup
	 */
	public String getIPBackup() {
		return IPBackup;
	}

	/**
	 * @param iPBackup the iPBackup to set
	 */
	public void setIPBackup(String iPBackup) {
		IPBackup = iPBackup;
	}

}
